# name : Leave one out dataset
# key : cv_leave_one_out_ds
# contributor: Shuguang Sun
# --
proc sort data=${1:dsin} out=${2:dsout};
  by ${3:ids};
run;

proc sort data=$1
  out=$2_id (keep=$3) nodupkey;
  by $3;
run;

data $2_id;
  set $2_id end=eof;
  _foldid_ = _N_;
  by $3;
  IF eof THEN CALL SYMPUTX('_nobs_', _N_);
  _$3 = $3;$0
run;

%put &=_nobs_.;

data $2_fold;
  merge $2 $2_id;
  by $3;
run;

data $2_fold;
  set $2_fold;
  DO _fold_ = 1 TO &_nobs_. BY 1;
    output;
    ** IF _fold_ NE _foldid_ THEN output;
    END;
run;

data $2_fold (drop=_foldid_);
  set $2_fold;
  where _fold_ NE _foldid_;
run;

proc sort data=$2_fold;
  by _fold_;
run;

proc sort data=$2_id;
  by _foldid_;
run;

data $2_fold;
  merge $2_fold $2_id (keep=_foldid_ $3 rename=($3=_$3_ _foldid_=_fold_));
  by _fold_;
run;

proc sort data=$2_fold;
  by _fold_ _$3_ $3;
run;
